const express = require("express");
const { db } = require("../database");
// 创建路由对象，使得用户登录状态检查的中间件只作用于部分路由。
const router = express.Router();
const { useAuthorization } = require("./base");
router.use(useAuthorization);
//新增考勤相关信息
router
    .post("/",async(req,res)=>{
        const{personId,startWork,offDuty} = req.body;
       const attend=await db.insert("insert into meetingroom (personId,startWork,offDuty) values (?, ?, ?)",
       [personId,startWork,offDuty]
       );
       const add=await db.findOne`SELECT * FROM attendance where id=${attend} `
       res.send({
        code:200,
        message:"添加成功",
        result:add
       });
    })


    //查询考勤信息
    .get("/kao", async (req, res) => {
        const att = await db.select`SELECT * FROM attendance`;
        res.send({
            code: 200,
            message: "查询考勤成功",
            result: att
        })
    })
 
    //修改考勤信息
    .put("/xi/:tid",
    async (req,res)=>{
        const mess=await db.findOne`select * from attendance where id = ${req.params.tid}`;
        if(!mess){
            return res.send({
              code:-1,
              message:"该考勤不存在！"
            })
          }
          const{personId,startWork,offDuty} = req.body;
          await db.run`update attendance set personId = ${personId}, startWork = ${startWork}, offDuty = ${offDuty} where id = ${req.params.tid}`
          const messes=await db.findOne`select * from attendance where id = ${req.params.tid}`;
          res.send({
           code:200,
           message:"考勤更新成功",
           result:messes
          });
        }
    )

//删除考勤信息
.delete("/delete/:tid",async(req,res)=>{
    const attendance=await db.select`select * from attendance where id = ${req.params.tid}`
    if(!attendance){
        return res.send({
            code:-1,
            message:"该考勤信息不存在！"
          })
    }
    await db.run`delete from attendance where id = ${req.params.tid}`
    res.send({
        code:200,
        message:"删除成功",
       })
})



// 将路由作为中间件挂接在 / 根路由上。
const registerRouter = (app) => app.use("/attendance", router);

module.exports = { registerRouter };